package com.henry.chatkit.input

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.viewpager2.widget.ViewPager2
import com.henry.chatkit.R

class InputMoreLayout : LinearLayout {

    constructor(context: Context?) : super(context) {
        initViews()
    }
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initViews()
    }
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initViews()
    }

    private fun initViews() {
        inflate(context, R.layout.chat_input_more_layout, this)
    }

    fun initView(actions: List<InputMoreActionUnit>) {
        val viewPager: ViewPager2 = findViewById(R.id.viewPager)
        val indicator = findViewById<ViewGroup>(R.id.actions_page_indicator)

        val adapter = MorePagerAdapter(actions, context)
        viewPager.adapter = adapter

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                setIndicator(indicator, adapter.itemCount, position)
            }
        })
        setIndicator(indicator, adapter.itemCount, 0)

    }

    /**
     * 设置页码
     */
    private fun setIndicator(indicator: ViewGroup, total: Int, current: Int) {
        if (total <= 1) {
            indicator.visibility = GONE
            indicator.removeAllViews()
        } else {
            indicator.visibility = VISIBLE
            indicator.removeAllViews()
            for (i in 0 until total) {
                val imgCur = ImageView(indicator.context)
                imgCur.id = i
                // 判断当前页码来更新
                if (i == current) {
                    imgCur.setBackgroundResource(R.drawable.page_selected)
                } else {
                    imgCur.setBackgroundResource(R.drawable.page_unselected)
                }
                indicator.addView(imgCur)
            }
        }
    }

}